const { request, response } = require('express')
const { info } = require('../api/user')
const { asyncException } = require('../util/async-execption')
const { AuthException } = require('../util/exception')

exports.AuthMiddleWare = function (isRedirect) {
    /**
    * 
    * @param {request} req 
    * @param {response} res 
    * @param {Function} next 
    */
    return asyncException(async function (req, res, next) {
        const cookie = {}
        req.headers['cookie'] && req.headers['cookie'].split(';').forEach(item => {
            const array = item.trim().split('=')
            cookie[array[0]] = array[1]
        })
        if (cookie.token) {
            const token = cookie.token
            const data = await info(token)
            if (data.code === 20000) {
                req.__user__ = data.data
                next()
            } else {
                if (isRedirect) {
                    throw new AuthException()
                } else {
                    next()
                }
            }
        } else {
            if (isRedirect) {
                throw new AuthException()
            } else {
                next()
            }
        }
    })
}